package com.ujs.statistics.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ujs.statistics.entity.Daily;
import com.ujs.statistics.entity.vo.EchartsVo;
import com.ujs.statistics.feign.UcenterFeignService;
import com.ujs.statistics.mapper.DailyMapper;
import com.ujs.statistics.service.DailyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * <p>
 * 网站统计日数据 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2023-09-04
 */
@Service
public class DailyServiceImpl extends ServiceImpl<DailyMapper, Daily> implements DailyService {
    @Autowired
    @Qualifier("com.ujs.statistics.feign.UcenterFeignService")
    private UcenterFeignService centerFeignService;

    @Override
    public void registerCount(String day) {
        // 添加记录之前，先删除表中相同日期的记录
        QueryWrapper<Daily> wrapper = new QueryWrapper<Daily>().eq("date_calculated", day);
        baseMapper.delete(wrapper);

        // 人数数据添加到数据库
        Integer count = centerFeignService.countRegister(day);
        Daily daily = new Daily();
        daily.setRegisterNum(count);
        daily.setDateCalculated(day);

        daily.setVideoViewNum(RandomUtils.nextInt(100, 200));
        daily.setLoginNum(RandomUtils.nextInt(100, 200));
        daily.setCourseNum(RandomUtils.nextInt(100, 200));
        baseMapper.insert(daily);
    }

    @Override
    public Map<String, Object> getData(EchartsVo echartsVo) {
        String begin = echartsVo.getBegin();
        String end = echartsVo.getEnd();
        List<Daily> dailyList = baseMapper.getData(begin, end);
        System.out.println("dailyList+++++++++" + dailyList);
        ArrayList<Integer> numDataList = new ArrayList<>();
        ArrayList<String> date_calculatedList = new ArrayList<>();
        for (Daily daily : dailyList) {
            numDataList.add(getNumFromDaily(echartsVo.getType(), daily));
            date_calculatedList.add(daily.getDateCalculated());
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("numDataList", numDataList);
        map.put("date_calculatedList", date_calculatedList);
        return map;
    }

    private Integer getNumFromDaily(String type, Daily daily) {
        if ("login_num".equals(type)) return daily.getLoginNum();
        if ("register_num".equals(type)) return daily.getRegisterNum();
        if ("video_view_num".equals(type)) return daily.getVideoViewNum();
        if ("course_num".equals(type)) return daily.getCourseNum();
        return 0;
    }
}
